package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SecKillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SecKillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CHCHE_PREFIX = "seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码
    @Override
    public void uploadSeckillSkuLasest3Days() {
        //1.扫描最近三天需要参与秒杀的活动
        R session = couponFeignService.getLates3DaySession();
        if(session.getCode() == 0){
            //上架商品
            List<SeckillSessionsWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //1.缓存活动信息
            saveSessionInfos(sessionData);
            //2.缓存活动的关联商品信息
            saveSessionSkuInfo(sessionData);
        }


    }

    public List<SecKillSkuRedisTo> blockHandlerSeckill(BlockException e){
        log.error("getCurrentSeckillSkusResource被限流了。。。");
        return null;
    }

    /**
     * 返回当前时间可以参与的秒杀商品信息
     *   blockHandler  函数会在原方法被流/降级/系统保护的时候调用，而fallback函数会针对所有类型的异常
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandlerSeckill")
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();

        try(Entry entry = SphU.entry("seckillSkus")){
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            String curKey = null;
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if(time >= start && time <= end){
                    curKey = key;
                    break;
                }
            }
            //2.获取这个秒杀场次需要的所有商品信息
            if(curKey != null){
                List<String> range = redisTemplate.opsForList().range(curKey, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if(list != null){
                    List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                        SecKillSkuRedisTo redisTo = JSON.parseObject(item, SecKillSkuRedisTo.class);
                        //redisTo.setRandomCode(null);  当前秒杀开始了就需要随机码
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
            }
        }catch (BlockException e){
            log.error("资源被限流{}",e.getMessage());
        }



        return null;
    }

    @Override
    public SecKillSkuRedisTo getskuSeckillInfo(Long skuId) {
        //1.找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if(keys != null && keys.size() > 0){
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if(Pattern.matches(regx,key)){
                    String json = hashOps.get(key);
                    SecKillSkuRedisTo skuRedisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    //随机码
                    long curTime = new Date().getTime();
                    if(curTime >= skuRedisTo.getStartTime()
                            && curTime <= skuRedisTo.getEndTime()){
                    }else {
                        skuRedisTo.setRandomCode(null);
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    //TODO 上架秒杀商品的时候，每个数据都有过期时间，
    //TODO 秒杀后续的流程，简化了收货地址等信息，
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        MemberResponseVo respVO = LoginUserInterceptor.loginUser.get();
        //获取秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
        String s = hashOps.get(killId);
        if(StringUtils.isEmpty(s)){
            return null;
        }

        SecKillSkuRedisTo redis = JSON.parseObject(s, SecKillSkuRedisTo.class);
        //校验合法性
        Long startTime = redis.getStartTime();
        Long endTime = redis.getEndTime();
        Long curTime = new Date().getTime();

        long ttl = endTime - startTime;
        //校验时间 (上架时)
        if(curTime < startTime || curTime > endTime){
            return null;
        }

        //校验随机码和商品id
        String randomCode = redis.getRandomCode();
        String skuId = redis.getPromotionSessionId() + "_"+redis.getSkuId();
        if(!randomCode.equals(key) || !killId.equals(skuId)){
            return null;
        }
        //校验购物数量是否合理
        if(num > redis.getSeckillLimit()){
            return null;
        }
        //验证买家是不买过  幂等性;如果只要秒杀成功就去占位 userId_SessionId_skuId 作为key
        String redisKey = respVO.getId() + "_" + skuId;
        //自动过期
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if(!aBoolean){ //占位不成功，说明己经买过
            return null;
        }
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
        //boolean b = semaphore.tryAcquire(num,100,TimeUnit.MILLISECONDS);
        boolean b = semaphore.tryAcquire(num);
        if(!b){
            return null;
        }
        //秒杀成功
        //快速下单，发送给MQ消息
        String timeId = IdWorker.getTimeId();
        SecKillOrderTo orderTo = new SecKillOrderTo();
        orderTo.setOrderSn(timeId);
        orderTo.setMemberId(respVO.getId());
        orderTo.setNum(num);
        orderTo.setPromotionSessionId(redis.getPromotionSessionId());
        orderTo.setSkuId(redis.getSkuId());
        orderTo.setSeckillPrice(redis.getSeckillPrice());
        rabbitTemplate.convertAndSend("order-event-exchange",
                "order.seckill.order",orderTo);
        long s2 = System.currentTimeMillis();
        log.info("耗时s2 - s1====" + (s2 - s1) + "ms");
        return timeId;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions){
        if(sessions == null){
            return;
        }
        sessions.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if(!hasKey){
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_"+ item.getSkuId().toString()).collect(Collectors.toList());
                //缓存活动信息
                redisTemplate.opsForList().leftPushAll(key,collect);
            }


        });
    }

    private void saveSessionSkuInfo(List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(session->{
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CHCHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo->{
                //缓存商品
                SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                //4.随机码?
                String token = UUID.randomUUID().toString().replace("-","");
                if(!ops.hasKey(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString())){

                    //1.sku的基本信息
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if(skuInfo.getCode() == 0){
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(info);
                    }
                    //2.sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);

                    //3.设置当前商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    redisTo.setRandomCode(token);

                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString(),jsonString);
                    //如果当前这个场次的商品的库存信息己经上架就不需要上架
                    //5.使用库存作为分布式信号量  限流;
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }
}
